package com.changgou.search.controller;

import com.changgou.entity.Result;
import com.changgou.search.dao.SearchMapper;
import com.changgou.search.service.EsManagerService;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * @author BAO
 * @version V1.0
 * @Package com.changgou.search.controller
 * @date 2020/12/9 18:41
 * @description:
 */
@RestController
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private EsManagerService esManagerService;

    @Autowired
    private SearchService searchService;

    @GetMapping("/createIndexAndMapping")
    public Result createIndexAndMapping(){
        esManagerService.createIndexAndMapping();
        return Result.success("createIndexAndMapping success",null);
    }

    @GetMapping("/importBySpuId/{spuId}")
    public Result importDataToESBySpuId(@PathVariable String spuId){
        esManagerService.importDataToESBySpuId(spuId);
        return Result.success("importDataToESBySpuId success",null);
    }

    @GetMapping("/importAll")
    public Result importAll(){
        esManagerService.importAll();
        return Result.success("importAll success",null);
    }

    @GetMapping("/search")
    public Result search(@RequestParam Map<String,String> searchMap) throws Exception {
        handlerSearchMap(searchMap);
        Map search = searchService.search(searchMap);
        return Result.success("search success",search);
    }

    //对搜索入参带有特殊符号进行处理
    public void handlerSearchMap(Map<String,String> searchMap){

        if(null != searchMap){
            Set<Map.Entry<String, String>> entries = searchMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if(entry.getKey().startsWith("spec_")){
                    searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
                }
            }
        }

    }

}
